﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Utilities;
using SPAutomaticListsPopulator.Helprers;
using SPAutomaticListsPopulator.Office;
using SPAutomaticListsPopulator.TreeView;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UploadDocLib01.ErrorHandlers;
using UploadDocLib01.Utilities;
using UploadDocLib01.Word;

namespace SPAutomaticListsPopulator
{
    public partial class Main : Form
    {

        #region properties/fields
        int selectedDocumentIndex = 0;
        SPWebApplicationCollection webApplications = null;
        SPList currentList = null;
        BindingList<PopulatedFieldSetting> bindingFieldList = null;
        Random rand = new Random();
        #endregion

        public Main()
        {
            InitializeComponent();
        }

        private void DisableAllTabs()
        {
            foreach (TabPage page in tabControl.TabPages)
            {
                ((Control)page).Enabled = false;
            }
        }


        private void Main_Load(object sender, EventArgs e)
        {
            DisableAllTabs();
            CbFileType.SelectedIndex = 0;
            lbGenerationResult.Text = "";
            SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>("");
            webApplications = service.WebApplications;
            foreach (SPWebApplication webApp in webApplications)
            {
                TreeNodeWebApplication appNode = new TreeNodeWebApplication(webApp.Name);
                appNode.Application = webApp;
                FarmTreeView.Nodes.Add(appNode);
               // appNode.Nodes.Add(new TreeNodeSites("Sites") { Application = webApp });
            }

            //Clicked on the Web Application

        }

        private void RemoveFakeNode(TreeNode node)
        {
            if (node.Nodes["fakeNode"] != null)
            {
                node.Nodes["fakeNode"].Remove();
            }
        }

        //private void FarmTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        private void FarmTreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
        }


        private void SetInitialDataGridSettings()
        {
            foreach (SPField field in currentList.Fields)
            {
                if (SPBuiltInFieldId.Contains(field.Id) && field.Id != SPBuiltInFieldId.Title)
                {
                    continue;
                }

                if (field.Hidden == true)
                {
                    continue;
                }
                if (field.ShowInNewForm == false)
                {
                    continue;
                }

                PopulatedFieldSetting fieldSetting = GetFieldSetting(field);

                bindingFieldList.Add(fieldSetting);
            }
        }

        private PopulatedFieldSetting GetFieldSetting(SPField field)
        {
            PopulatedFieldSetting fieldSetting = new PopulatedFieldSetting()
            {
                InternalName = field.InternalName,
                Title = field.Title,
                FieldType = field.Type.ToString()
            };

            if (field is SPFieldLookup && field.Type != SPFieldType.Lookup)
            {
                if (((SPFieldLookup)field).AllowMultipleValues)
                {
                    fieldSetting.maxNumberOfChoices = 3;
                }
            }

            switch (field.Type)
            {
                case SPFieldType.MultiChoice:
                    fieldSetting.maxNumberOfChoices = ((SPFieldMultiChoice)field).Choices.Count;
                    break;
                case SPFieldType.Lookup:
                    if (((SPFieldLookup)field).AllowMultipleValues)
                    {
                        fieldSetting.maxNumberOfChoices = 3;
                    }
                    break;
                case SPFieldType.Note:
                    fieldSetting.InitialValue = field.Title + " " + field.Title + " " + field.Title;
                    break;
                case SPFieldType.DateTime:
                    fieldSetting.minDate = DateTime.Now.AddDays(-90);
                    fieldSetting.maxDate = DateTime.Now.AddDays(90);

                    break;
                case SPFieldType.Invalid:
                    if (field.TypeAsString.Contains("TaxonomyFieldTypeMulti"))
                    {
                        TaxonomyField taxField = (TaxonomyField)field;
                        TaxonomySession taxonomySession = new TaxonomySession(currentList.ParentWeb.Site);
                        TermStore termStore = taxonomySession.TermStores.First(x => x.Id == taxField.SspId);
                        TermSet termSet = termStore.GetTermSet(taxField.TermSetId);
                        TermCollection terms = termSet.Terms;
                        fieldSetting.maxNumberOfChoices = terms.Count;
                    }
                    break;
            }

            if (field.PreviewValueTyped != null && field.Type != SPFieldType.Note)
            {
                fieldSetting.InitialValue = field.PreviewValueTyped.ToString();
            }
            return fieldSetting;
        }
        Dictionary<string, SPList> listsCache = new Dictionary<string, SPList>();
        private void button1_Click_1(object sender, EventArgs e)
        {
            selectedDocumentIndex = CbFileType.SelectedIndex;
            lbGenerationResult.Text = string.Empty;
            BtnGenerateItems.Enabled = false;
            FarmTreeView.Enabled = false;
            backgroundWorkerGenerateListItems.RunWorkerAsync();
        }

        //runs on UI thread
        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            mainProgressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lbGenerationResult.Text = "Generation complete!";

            LbItemsCount.Text = currentList.ItemCount.ToString();
            BtnGenerateItems.Enabled = true;
            mainProgressBar.Value = 0;
            FarmTreeView.Enabled = true;
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            Dictionary<string, SPListItemCollection> listsCacheItems = new Dictionary<string, SPListItemCollection>();
            SPWeb web_parent = currentList.ParentWeb;

            using (SPSite site = new SPSite(web_parent.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(web_parent.ID))
                {
                    currentList = web.GetList(SPUrlUtility.CombineUrl(currentList.ParentWeb.Url, currentList.RootFolder.Url));
                    for (int i = 0; i < numItemsToCreate.Value; i++)
                    {
                        int percentageComplete = (int)((float)i / (float)numItemsToCreate.Value * 100);
                        worker.ReportProgress(percentageComplete);
                        SPListItem item = null;
                        if (currentList is SPDocumentLibrary)
                        {
                            item = GenerateDocument(item);
                        }
                        else
                        {
                            item = currentList.AddItem();
                        }

                        FillListItemFields(listsCacheItems, web, i, item);
                        item.Update();
                    }
                }
            }
        }

        private SPListItem GenerateDocument(SPListItem item)
        {
            SPDocumentLibrary library = currentList as SPDocumentLibrary;
            string documentName = RandomHelper.RandomString(8, true);

            string txtExtension = ".txt";
            string docExtension = ".docx";
            string excelExtension = ".xlsx";
            string pngExtension = ".gif";

            //TODO: dispose stream?
            MemoryStream docStream = new MemoryStream();
            StreamWriter writer = new StreamWriter(docStream);

            //TODO: change to switch:
            if (selectedDocumentIndex == 0)
            {
                documentName += txtExtension;
                writer.Write(documentName + " Content");
                writer.Flush();
            }
            else if (selectedDocumentIndex == 1)
            {
                documentName += docExtension;
                DocumentBuilder.GenerateWordDocument(docStream, documentName + " Content");
            }
            else if (selectedDocumentIndex == 2)
            {
                documentName += excelExtension;
                DocumentBuilder.GenerateExcelDocument(docStream, documentName + " Content");
            }
            else if (selectedDocumentIndex == 3)
            {
                documentName += pngExtension;
                SPAutomaticListsPopulator.Helprers.Image.CreateImage(docStream, documentName + " Content");
                // g.Dispose();
                // image.Dispose();
            }

            SPFile file = library.RootFolder.Files.Add(documentName, docStream, true);
            writer.Flush();
            item = file.Item;
            return item;
        }

        private SPListItem FillListItemFields(Dictionary<string, SPListItemCollection> listsCacheItems, SPWeb web, int i, SPListItem item)
        {
            foreach (PopulatedFieldSetting fieldSetting in bindingFieldList)
            {
                string initialValue = fieldSetting.InitialValue;
                SPField field = currentList.Fields.GetFieldByInternalName(fieldSetting.InternalName);

                if (field is SPFieldLookup && field.Type != SPFieldType.Lookup)
                {
                    GenerateValueForLookupField(field, web, listsCacheItems, fieldSetting, item);
                }

                if (ListUtils.isFieldValueEmpty(item[field.Id]) == false)
                {
                    continue;
                }

                switch (field.Type)
                {
                    case SPFieldType.Text:
                    case SPFieldType.Note:
                            item[field.Id] = initialValue + i;
                        break;
                    case SPFieldType.Choice:
                            string choiceValue = RandomHelper.RandomArrayItem(((SPFieldChoice)field).Choices).ToString();
                            item[field.Id] = choiceValue;
                        break;

                    case SPFieldType.MultiChoice:
                            item[field.Id] = RandomHelper.RandomMultiChoiceValue(((SPFieldMultiChoice)field).Choices, fieldSetting.minNumberOfChoices, fieldSetting.maxNumberOfChoices);

                        break;
                    case SPFieldType.Lookup:
                        GenerateValueForLookupField(field, web, listsCacheItems, fieldSetting, item);
                        break;

                    case SPFieldType.URL:
                        item[field.Id] = RandomHelper.RandomSPFieldUrlValue();
                        break;
                    case SPFieldType.User:
                        //TODO: random user
                        break;
                    case SPFieldType.DateTime:
                        DateTime date = RandomHelper.RandomDate(rand, fieldSetting.minDate, fieldSetting.maxDate);
                        item[field.Id] = SPUtility.CreateISO8601DateTimeFromSystemDateTime(date);
                        break;
                    case SPFieldType.Boolean:
                        item[field.Id] = RandomHelper.RandomBool();
                        break;
                    case SPFieldType.Invalid:
                        if (field.TypeAsString.Contains("TaxonomyFieldType"))
                        {
                            //TODO: cache taxonomy:
                            TaxonomyField taxField = (TaxonomyField)field;
                            TaxonomySession taxonomySession = new TaxonomySession(web.Site);
                            TermStore termStore = taxonomySession.TermStores.First(x => x.Id == taxField.SspId);
                            TermSet termSet = termStore.GetTermSet(taxField.TermSetId);
                            TermCollection terms = termSet.Terms;

                            if (taxField.AllowMultipleValues == false)
                            {
                                int setID = RandomHelper.RandomNumber(0, terms.Count);
                                TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field);
                                taxonomyFieldValue.TermGuid = terms[setID].Id.ToString();
                                taxonomyFieldValue.Label = terms[setID].Name;
                                item[field.Title] = taxonomyFieldValue;
                            }
                            else
                            {
                                TaxonomyFieldValueCollection taxonomyFieldValuecollection = new TaxonomyFieldValueCollection(field);
                                List<Term> availableTerms = terms.Cast<Term>().ToList();
                                int numberOfValues = RandomHelper.RandomNumber(fieldSetting.minNumberOfChoices, fieldSetting.maxNumberOfChoices);
                                for (int k = 0; k < numberOfValues; k++)
                                {
                                    int setID = RandomHelper.RandomNumber(0, availableTerms.Count);
                                    TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field);
                                    taxonomyFieldValue.TermGuid = availableTerms[setID].Id.ToString();
                                    taxonomyFieldValue.Label = availableTerms[setID].Name;
                                    taxonomyFieldValuecollection.Add(taxonomyFieldValue);
                                    availableTerms.Remove(availableTerms[setID]);
                                }
                                item[field.Title] = taxonomyFieldValuecollection;
                            }
                        }
                        break;
                    case SPFieldType.Number:
                    case SPFieldType.Integer:
                        item[field.Id] = RandomHelper.RandomNumber(0, 99999);
                        break;
                    case SPFieldType.Counter:
                        break;
                    case SPFieldType.Currency:
                        item[field.Id] = RandomHelper.RandomNumber(0, 99999);
                        break;
                }
            }
            return item;
        }


        private SPListItem FillListItemFieldsForUpdate( SPWeb web, SPListItem item)
        {
            foreach (PopulatedFieldSetting fieldSetting in bindingFieldList)
            {
                string initialValue = fieldSetting.InitialValue;
                SPField field = currentList.Fields.GetFieldByInternalName(fieldSetting.InternalName);

                switch (field.Type)
                {
                    case SPFieldType.Text:
                    case SPFieldType.Note:
                    case SPFieldType.Choice:
                    case SPFieldType.MultiChoice:
                            item[field.Id] = initialValue;
                        break;

                    case SPFieldType.Lookup:
                       // GenerateValueForLookupField(field, web, listsCacheItems, fieldSetting, item);
                        break;

                    case SPFieldType.URL:
                       // item[field.Id] = RandomHelper.RandomSPFieldUrlValue();
                        break;
                    case SPFieldType.User:
                        //TODO: random user
                        break;
                    case SPFieldType.DateTime:
                        DateTime date = DateTime.Parse(fieldSetting.InitialValue);
                        item[field.Id] = SPUtility.CreateISO8601DateTimeFromSystemDateTime(date);
                        break;
                    case SPFieldType.Boolean:
                       // item[field.Id] = RandomHelper.RandomBool();
                        break;
                    case SPFieldType.Invalid:
                        
                        break;
                    case SPFieldType.Number:
                    case SPFieldType.Integer:
                        item[field.Id] = item[field.Id] = initialValue;
                        break;
                    case SPFieldType.Counter:
                        break;
                   
                }
            }
            return item;
        }


        private void GenerateValueForLookupField(SPField field, SPWeb web, Dictionary<string, SPListItemCollection> listsCacheItems,
    PopulatedFieldSetting fieldSetting, SPListItem item)
        {
         
            SPFieldLookup fieldLookup = (SPFieldLookup)field;
            if (string.IsNullOrEmpty(fieldLookup.LookupList))
            {
                return;
            }
            SPList lookupList = null;
            SPListItemCollection lookupItems = null;
            if (listsCache.ContainsKey(fieldLookup.LookupList) == false)
            {
                lookupList = web.Lists[new Guid(fieldLookup.LookupList)];
                listsCache.Add(fieldLookup.LookupList, lookupList);
            }
            if (listsCacheItems.ContainsKey(fieldLookup.LookupList) == false)
            {
                lookupList = listsCache[fieldLookup.LookupList];
                SPQuery query = new SPQuery();
                query.RowLimit = 20;
                lookupItems = lookupList.GetItems(query);
                listsCacheItems.Add(fieldLookup.LookupList, lookupItems);
            }
            if (listsCacheItems.ContainsKey(fieldLookup.LookupList) == false)
            {
                return;
            }

            lookupItems = listsCacheItems[fieldLookup.LookupList];

            if (lookupItems.Count == 0)
            {
                return;
            }

            if (fieldLookup.AllowMultipleValues)
            {
                SPFieldLookupValueCollection coll = new SPFieldLookupValueCollection();
                for (int k = fieldSetting.minNumberOfChoices; k < fieldSetting.maxNumberOfChoices; k++)
                {
                    int newLookupID = RandomHelper.RandomNumber(0, lookupItems.Count);
                    coll.Add(new SPFieldLookupValue(lookupItems[newLookupID].ID, lookupItems[newLookupID].Title));
                }
                item[field.Id] = coll;
            }
            else
            {
                int newLookupID = RandomHelper.RandomNumber(0, lookupItems.Count);
                item[field.Id] = new SPFieldLookupValue(lookupItems[newLookupID].ID, lookupItems[newLookupID].Title);
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FarmTreeView.SelectedNode.Nodes.Clear();
            listsCache.Clear();
            FarmTreeView.SelectedNode.Nodes.Add(new TreeNode() { Name = "fakeNode" });
            FarmTreeView.SelectedNode.Collapse();
        }

        private void FarmTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //List node clicked
            if (e.Node is TreeNodeList)
            {
                if ( currentList == ((TreeNodeList)e.Node).List)
                {
                    this.Cursor = Cursors.Default;
                    return;
                }
                ((Control)tabPageList).Enabled = true;
                try
                {
                    currentList = ((TreeNodeList)e.Node).List;
                    linkListName.Text = currentList.Title;
                    linkListName.Tag = SPUrlUtility.CombineUrl(currentList.ParentWeb.Url, currentList.RootFolder.Url);
                    bindingFieldList = new BindingList<PopulatedFieldSetting>();

                    //add Title treeNodeField to SPDocumentLibrary:
                    if (currentList is SPDocumentLibrary)
                    {
                        CbFileType.Enabled = true;
                        bindingFieldList.Add(new PopulatedFieldSetting()
                        {
                            InitialValue = "Blank Title ",
                            InternalName = "Title",
                            Title = "Title"
                        });
                    }
                    else
                    {
                        CbFileType.Enabled = false;
                    }

                    SetInitialDataGridSettings();

                    gridViewGeneratedFields.DataSource = bindingFieldList;
                    gridViewUpdatedFields.DataSource = bindingFieldList;

                    txtXML.Text = XMLHelper.PrintXML(currentList.SchemaXml);
                    LbItemsCount.Text = currentList.ItemCount.ToString();
                }
                catch (Exception ex)
                {
                    LbError.Text = ex.Message;
                }

                this.Cursor = Cursors.Default;
                return;
            }
        }

        private void FarmTreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node is TreeNodeList )
            {
                this.Cursor = Cursors.WaitCursor;
            }
        }

        private void FarmTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            DisableAllTabs();
            CbFileType.Enabled = false;
            LbError.Text = "";
            lbGenerationResult.Text = "";

            AddChildNodes(e);

            this.Cursor = Cursors.Default;

        }

        private void AddChildNodes(TreeViewCancelEventArgs e)
        {
            //Expanded the Web Application
            if (e.Node is TreeNodeWebApplication)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);

                    TreeNodeSites sitesNode = new TreeNodeSites("Sites");
                    sitesNode.Application = ((TreeNodeWebApplication)e.Node).Application;
                   
                    e.Node.Nodes.Add(sitesNode);
                }
                return;
            }

            //Expanded the Sites container
            if (e.Node is TreeNodeSites)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    foreach (SPSite site in ((TreeNodeSites)e.Node).Application.Sites)
                    {
                        TreeNodeSite siteNode = new TreeNodeSite(site.Url);
                        siteNode.Site = site;
                        e.Node.Nodes.Add(siteNode);
                    }
                }
                return;
            }

            //Expanded the Site Collection
            if (e.Node is TreeNodeSite)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    TreeNodeAllWebs websNode = new TreeNodeAllWebs("AllWebs");
                    websNode.Site = ((TreeNodeSite)e.Node).Site;
                    e.Node.Nodes.Add(websNode);
                }
                return;
            }

            //Expanded the Webs container
            if (e.Node is TreeNodeAllWebs)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    foreach (SPWeb web in ((TreeNodeAllWebs)e.Node).Site.AllWebs)
                    {
                        TreeNodeWeb webNode = new TreeNodeWeb(web.Title);
                        webNode.Web = web;
                        e.Node.Nodes.Add(webNode);
                    }
                }
                return;
            }

            //Expanded the Web
            if (e.Node is TreeNodeWeb)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    TreeNodeWebs websNode = new TreeNodeWebs("Webs");
                    websNode.Web = ((TreeNodeWeb)e.Node).Web;
                    e.Node.Nodes.Add(websNode);

                    TreeNodeLists listsNode = new TreeNodeLists("Lists");
                    listsNode.Web = ((TreeNodeWeb)e.Node).Web;
                    e.Node.Nodes.Add(listsNode);
                }
            }

            //Expanded WebsContainer
            if (e.Node is TreeNodeWebs)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    foreach (SPWeb web in ((TreeNodeWebs)e.Node).Web.Webs)
                    {
                        TreeNodeWeb webNode = new TreeNodeWeb(web.Title);
                        webNode.Web = web;
                        e.Node.Nodes.Add(webNode);
                    }
                }
                return;
            }

            //Expanded ListsContainer
            if (e.Node is TreeNodeLists)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    foreach (SPList list in ((TreeNodeLists)(e.Node)).Web.Lists)
                    {
                        TreeNodeList listNode = new TreeNodeList(list.Title);
                        listNode.List = list;
                        e.Node.Nodes.Add(listNode);
                    }
                }
                return;
            }

            //Expanded the List
            if (e.Node is TreeNodeList)
            {
                RemoveFakeNode(e.Node);
                ((Control)tabPageList).Enabled = true;
                try
                {
                    if (e.Node.Nodes["Fields"] == null)
                    {
                        TreeNodeFields fieldsNode = new TreeNodeFields("Fields") { Name = "Fields" };
                        fieldsNode.List = ((TreeNodeList)e.Node).List;
                        e.Node.Nodes.Add(fieldsNode);
                    }
                }
                catch (Exception ex)
                {
                    LbError.Text = ex.Message;
                }

                return;
            }

            //Expanded the Fields container
            if (e.Node is TreeNodeFields)
            {
                if (e.Node.Nodes.Count == 1 && e.Node.Nodes["fakeNode"] != null)
                {
                    RemoveFakeNode(e.Node);
                    foreach (SPField field in ((TreeNodeFields)e.Node).List.Fields)
                    {
                        TreeNodeField fieldNode = new TreeNodeField(field.Title);
                        fieldNode.Field = field;
                        e.Node.Nodes.Add(fieldNode);
                    }
                }
            }

            //Expanded the Field Node
            if (e.Node is TreeNodeField)
            {
                ((Control)tabPageList).Enabled = true;
                RemoveFakeNode(e.Node);
                // RemoveFakeNode(e.Node);
                // SPField treeNodeField = (SPField)e.Node.Tag;
                return;
            }
        }

        private void linkListName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string URL = linkListName.Tag.ToString();
            Process.Start(URL);
        }

        private void btnBatchInsert_Click(object sender, EventArgs e)
        {
            BatchHelper.InsertItems(currentList, (int)numItemsToCreate.Value, bindingFieldList);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCaml.Text))
            {
                BatchHelper.RemoveItems(currentList, (int)numFirstItem.Value, (int)numLastItemId.Value);
            }
            else
            {
                BatchHelper.RemoveItems(currentList, txtCaml.Text);
            }
        }

        private void FarmTreeView_DoubleClick(object sender, EventArgs e)
        {
            if (this.FarmTreeView.SelectedNode is TreeNodeField)
            {
                TreeNodeField treeNodeField = (TreeNodeField)this.FarmTreeView.SelectedNode;
                PopulatedFieldSetting fieldSetting = this.GetFieldSetting(treeNodeField.Field);
                bindingFieldList.Add(fieldSetting);
            }
        }

        private void BtnFillEmptyFields_Click(object sender, EventArgs e)
        {
            lbGenerationResult.Text = string.Empty;
            BtnGenerateItems.Enabled = false;
            FarmTreeView.Enabled = false;
            backgroundWorkeUpdateListItems.RunWorkerAsync();
        }

        private void backgroundWorkeUpdateListItems_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            Dictionary<string, SPListItemCollection> listsCacheItems = new Dictionary<string, SPListItemCollection>();
            SPWeb web_parent = currentList.ParentWeb;

            using (SPSite site = new SPSite(web_parent.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(web_parent.ID))
                {
                    currentList = web.GetList(SPUrlUtility.CombineUrl(currentList.ParentWeb.Url, currentList.RootFolder.Url));

                    SPQuery query = new SPQuery() { RowLimit=2000};
                    SPListItemCollection items = currentList.GetItems(query);
                    for (int i = 0; i < items.Count; i++)//number of items to update.
                    {
                        int percentageComplete = (int)((float)i / (float)items.Count * 100);
                        worker.ReportProgress(percentageComplete);
                        SPListItem item = FillListItemFields(listsCacheItems, web, i, items[i]);
                        item.Update();
                    }
                }
            }
        }

        private void backgroundWorkeUpdateListItems_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            mainProgressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorkeUpdateListItems_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lbGenerationResult.Text = "Generation complete!";

            LbItemsCount.Text = currentList.ItemCount.ToString();
            BtnGenerateItems.Enabled = true;
            mainProgressBar.Value = 0;
            FarmTreeView.Enabled = true;
        }

        private void splitter1_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

        private void btnUpdateItems_Click(object sender, EventArgs e)
        {
           // BatchOperation operation = new BatchOperation(currentList, 500, true, true);

           int[] itemIds = tbUpdateItemIds.Text.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries).Select(x=>int.Parse(x)).ToArray();
            
                    foreach (int id in itemIds)
                    {
                         SPListItem item  = currentList.GetItemById(id);
                         item = FillListItemFieldsForUpdate(currentList.ParentWeb, item);
                         item.SystemUpdate();
                    }
        }

        private void btnBatchInsert_Click_1(object sender, EventArgs e)
        {

        }
    }
}
